package com.xdxc.JwtGenaner;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.List;

public class JwtUtil {

    private static final String SECRET_KEY = "5Xg7mzL8hN6JkRtQvSq2dsDFSFSDYGFYUFDFSG8FG78SDGFIAGRFG8Y9G0780N90N9VG8NVH980NH98S09NH80NH980NH98SVG0NH9SVGD9NH0D9NH0ESG0NH98SVGH9V9GFM0SPOICBJIOIJFDPSH98HBSU9DGFIDJIPFIPSNOHuYwV1x3Zc4Fb9Ae0KiUjWnMlCoDpBfThGdHyrOaI7P";
    // 将字符串密钥转换为 Key 对象
    private static final Key SIGNING_KEY = Keys.hmacShaKeyFor(Base64.getDecoder().decode(SECRET_KEY));
    private static final long EXPIRATION_TIME = 3600 * 1000 *10; // 1小时

    // 生成Token
    public static String generateToken(String identifier,Long userId, List<String> roles) {
        return Jwts.builder()
                .setSubject(identifier)
                .claim("roles", roles) // 嵌入角色列表
                .claim("userId", userId) // 新增用户ID字段
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SIGNING_KEY) // 使用 HS512 算法
                .compact();
    }

    // 解析Token
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SIGNING_KEY)
                .parseClaimsJws(token)
                .getBody();
    }
}